package adb

import (
	log2 "answer5/log"
	"bytes"
	"fmt"
	"image"
	"image/png"
	"io/ioutil"
	"log"
	"net/http"
	"os/exec"
	"strconv"
	"time"
)

var(
	port = "21513"
)

func GetSnapshot() (img image.Image, err error) {
	go log2.LogPrint("开始截图")

	cmd := exec.Command("adb", "shell", "screencap", "-p")
	var out bytes.Buffer
	cmd.Stdout = &out

	if err = cmd.Run(); err != nil {
		log.Println(err)
		go log2.ErrorPrint(err.Error())
		return nil, err
	}
	x := bytes.Replace(out.Bytes(), []byte("\r\r\n"), []byte("\n"), -1)

	img, err = png.Decode(bytes.NewReader(x))

	return
}

func Restart(){
	exec.Command("adb","stop-server").Run()
	cmdOut,_ := exec.Command("adb","start-server").Output()
	go log2.LogPrint("start adb :" + string(cmdOut))
	cmdOut,_ = exec.Command("adb","connect","127.0.0.1:"+port).Output()
	go log2.LogPrint("连接逍遥游 :" + string(cmdOut))
}

func StartUiautomator(){
	exec.Command("adb","stop-server").Run()
	cmdOut,_ := exec.Command("adb","start-server").Output()
	fmt.Println("start adb :" + string(cmdOut))
	go log2.LogPrint("start adb :" + string(cmdOut))
	cmdOut,_ = exec.Command("adb","connect","127.0.0.1:"+port).Output()
	fmt.Println("连接逍遥游 :" + string(cmdOut))
	go log2.LogPrint("连接逍遥游 :" + string(cmdOut))
	cmdOut,_ = exec.Command("adb","shell","/data/local/tmp/atx-agent","server", "-d").Output()
	fmt.Println("atx-agent :" + string(cmdOut))
	go log2.LogPrint("atx-agent :" + string(cmdOut))
	cmdOut,_ = exec.Command("adb","forward","tcp:5651","tcp:7912").Output()
	fmt.Println("adb forward:" + string(cmdOut))
	go log2.LogPrint("adb forward:" + string(cmdOut))
}

func GetHierarchy()(*[]byte){
	resp, err := http.Get("http://127.0.0.1:5651/dump/hierarchy")
	if err != nil{
		fmt.Println("GetHierarchy:" + err.Error())
		go log2.LogPrint("GetHierarchy:" + err.Error())
		return nil
	}else {
		defer resp.Body.Close()
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil{
		go log2.LogPrint("GetHierarchy:" + err.Error())
	}
	fmt.Println(string(body))
	return &body

	//var jsonObj xiaohongshu.XiaohongshuQuestionRaw
	//err = json.Unmarshal(body, &jsonObj)
	//if err != nil {
	//	go log2.LogPrint("GetHierarchy(json):" + err.Error())
	//}
	//
	//
	//f, err := os.OpenFile("G:/hierarchy/"+ strconv.Itoa(int(time.Now().Unix())) +".txt", os.O_CREATE|os.O_WRONLY, 0644)
	//if err != nil {
	//	panic(err)
	//}
	//defer f.Close()
	//f.WriteString(jsonObj.Result)
}

func AdbShellInputTap(x, y int) {
	x2 := strconv.Itoa(x)
	y2 := strconv.Itoa(y)
	exec.Command("adb", "shell", "input", "tap", x2, y2).Run()
}

func TimeSleepDuration(x int) {
	time.Sleep(time.Duration(x) * time.Millisecond)
}

func UiAutomatorDump(){
	exec.Command("adb", "shell", "uiautomator", "dump", "--compressed", "/sdcard/Download/ui.xml").Run()

}

